package com.lottery.ruok.lottrey.retrofitModule;

import android.app.Activity;
import android.content.Context;
import android.support.v4.app.FragmentActivity;

import com.android.lib.dialog.NetWaitDialog;
import com.lottery.ruok.lottrey.BuildConfig;
import com.lottery.ruok.lottrey.MyApplication;
import com.lottery.ruok.lottrey.common.Common;
import com.lottery.ruok.lottrey.userInfo.UserInfo;
import com.lottery.ruok.lottrey.utils.PostSlackUtils;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import io.reactivex.observers.DisposableObserver;
import property.SharePreferenceProperties;
import utils.Utils;

import com.lottery.ruok.lottrey.utils.LoadIPUtil;

public abstract class RxSubscribe<T> extends DisposableObserver<T> {
    private NetWaitDialog netWaitDialog;
    private Context mActivity;
    private static long gapNoNetTime = 0;
    private static Lock lock = new ReentrantLock();

    public RxSubscribe(Context context) {
        this.mActivity = context;
    }

    @Override
    public void onNext(T t) {
        _onNext(t);
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();

        String message;
        if (e instanceof ServerException) {//自定义的ServerException，都是拥有status这个字段的
            message = e.getMessage();

            if (mActivity != null) {
                if (!message.equals("余额不足")) {
                    Utils.showToast(message);
                }
            }
        } else {
            message = Common.NO_NET;
            if (mActivity != null && Utils.getNetworkType(mActivity) != null) {
                int noNetTimes = UserInfo.getNoNet();
                if (++noNetTimes < 5) {      // 連網失敗, 會主動重試, 一下子就累計五六次, 甚至超過十次, 不會等到 User 感覺連網失敗十次.
                    UserInfo.setNoNet(noNetTimes);
                } else {
                    UserInfo.setNoNet(0);
                    changeDomain();
                }
            } else {
                if (mActivity != null) {
                    if (System.currentTimeMillis() - gapNoNetTime > 10000) {
                        if (!message.equals("请检查您的网络")) {
                            Utils.showToast(message);
                        }
                        gapNoNetTime = System.currentTimeMillis();
                    }
                }
            }
        }

        if (showDialog()) {
            netWaitDialog.dismissAllowingStateLoss();
        }
    }

    private void changeDomain() {
        if (lock.tryLock()) {
            try {
              /*  // 換備用 URL
                if (SharePreferenceProperties.getList("c_list", String.class) == null || SharePreferenceProperties.getList("c_list", String.class).size() == 0) {//拉取新的域名列表
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(String.format("https://lrgrmxx.com/android/%s/%s.txt", BuildConfig.COMPANY_CODE, BuildConfig.COMPANY_CODE))
                            .build();
                    Call call = client.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            if (response != null && response.body() != null) {
                                String json = response.body().string();
                                if (json != null && !json.trim().equals("")) {
                                    String[] arrays = json.replace("\n", "").split("@@@@@");//用@@@@@分割
                                    ArrayList<String> arrStr = new ArrayList<>(Arrays.asList(arrays));
//                                        SharePreferenceProperties.setObj("c_list", arrStr);

                                    //对c_list进行筛选，找出可以通用的域名
                                    handleDomain(arrStr);
                                }
                            }
                        }
                    });
                } else {
                    //c_list进行筛选，找出可以通用的域名
                    List<String> arrStr = SharePreferenceProperties.getList("c_list", String.class);
                    handleDomain(arrStr);
                }*/
                if (!BuildConfig.COMPANY_CODE.equals("speedup")) {

                    URL url = new URL(Common.APP_URL);
                    ArrayList<String> errorDomain = new ArrayList<>();
                    errorDomain.add(url.getHost());
                    new PostSlackUtils((Activity)mActivity,errorDomain).doPost();
                    if (UserInfo.mDomain.size() == 0) {
                        LoadIPUtil.getInstance((Activity) mActivity).downloadStandbyURL();
                    } else {
                        UserInfo.replaceDomain();
                    }
                }

            } catch (Exception e) {

            } finally {
                lock.unlock();
            }
        }
    }

    private void handleDomain(List arrStr) {
        if (arrStr.size() > 0) {
            SharePreferenceProperties.set("c_url", arrStr.get(0));

            Common.APP_URL = String.format(SharePreferenceProperties.get("c_url", "").toString(), MyApplication.UUID);
            RetrofitBase.resetRetrofit();

            arrStr.remove(0);
            SharePreferenceProperties.setObj("c_list", arrStr);
        }
    }

    @Override
    public void onComplete() {
        if (showDialog()) {
            netWaitDialog.dismissAllowingStateLoss();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (showDialog() && mActivity != null) {
            netWaitDialog = new NetWaitDialog();
            if (mActivity instanceof FragmentActivity) {
                netWaitDialog.show((FragmentActivity) mActivity);
            }
        }
    }

    protected abstract void _onNext(T t);

    protected abstract boolean showDialog();
}
